﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
//SQL Server Compact Edition

namespace DataBaseClient
{
    public partial class Form1 : Form
    {
        SqlCeConnection sqlcn;
        SqlCeCommand cmd;

        public Form1()
        {
            InitializeComponent();
            sqlcn = new SqlCeConnection(@"Data Source=C:\DataBaseTest\Database1.sdf");
            //Lokal databas på en av universitetetsdatorerna.
            this.GridviewBind();
        }

        private void submit_btn_Click(object sender, EventArgs e)
        {
            try
            {
                if (sqlcn.State != ConnectionState.Open)
                    sqlcn.Open();
                cmd = new SqlCeCommand("INSERT INTO Divers (DiverID,Name,Surname) VALUES ('" +
                    ID_txt.Text + "','" + name_txt.Text + "','" + surname_txt.Text + "')", sqlcn);
                cmd.ExecuteNonQuery();
                //SQL-query
                MessageBox.Show("Table updated successfully!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception");
            }
            finally
            {
                sqlcn.Close();
                cmd.Dispose();
            }
        }

        protected void GridviewBind()
        {
            try
            {
                if (sqlcn.State != ConnectionState.Open)
                    sqlcn.Open();
                dataGridView1.AutoGenerateColumns = true;
                DataTable dt = new DataTable();
                SqlCeDataAdapter sda = new SqlCeDataAdapter("SELECT * FROM Divers", sqlcn);
                sda.Fill(dt);
                dataGridView1.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception");
            }
            finally
            {
                sqlcn.Close();
            }
        }

        private void refresh_btn_Click(object sender, EventArgs e)
        {
            this.GridviewBind();
        }
    }
}
